import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 导入语言文件
import zhTranslation from './locales/zh/translation.json';
import enTranslation from './locales/en/translation.json';
import zhTWTranslation from './locales/zh-TW/translation.json';

// 语言资源
const resources = {
  zh: {
    translation: zhTranslation
  },
  en: {
    translation: enTranslation
  },
  'zh-TW': {
    translation: zhTWTranslation
  }
};

// 获取存储的语言设置或使用默认值
const getStoredLanguage = async () => {
  try {
    const storedLanguage = await AsyncStorage.getItem('language');
    return storedLanguage || 'zh'; // 默认使用中文
  } catch (error) {
    console.error('Failed to get language from storage:', error);
    return 'zh';
  }
};

// 初始化i18next
const initI18n = async () => {
  const language = await getStoredLanguage();
  
  i18n
    .use(initReactI18next)
    .init({
      resources,
      lng: language,
      fallbackLng: 'en',
      interpolation: {
        escapeValue: false
      },
      compatibilityJSON: 'v3' // 兼容性设置，在React Native中可能需要
    } as any);
};

// 初始化
initI18n();

export default i18n; 